package com.zifeng.study.springbootshirojwtdemo.handle;

import com.zifeng.study.springbootshirojwtdemo.exception.UnLoginException;
import com.zifeng.study.springbootshirojwtdemo.reponse.Response;
import com.zifeng.study.springbootshirojwtdemo.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author: 吴梓锋
 * @date: 2022/01/14 16:34:13
 * @version: 1.0.0
 * @description: 全局异常捕获Controller
 */
@Slf4j
@RestControllerAdvice
public class ExceptionInterceptorHandle {

    @ExceptionHandler(UnLoginException.class)
    public Response getUnLoginExceptionException(UnLoginException exception) {
        return ResponseUtil.error("401", "Token校验失败！", exception.getMessage());
    }

    @ExceptionHandler(AuthorizationException.class)
    public Response getUnauthenticatedException(AuthorizationException exception) {
        return ResponseUtil.error("401", "权限校验失败！", exception.getMessage());
    }

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Response exception(HttpServletRequest request, MethodArgumentNotValidException exception) {
        BindingResult result = exception.getBindingResult();
        final List<FieldError> fieldErrors = result.getFieldErrors();
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < fieldErrors.size(); i++) {
            builder.append(i + 1).append("、").append(fieldErrors.get(i).getDefaultMessage()).append(". ");
        }

        return ResponseUtil.error(builder.toString());
    }

}
